package com.zzl.alligator.framework.security.hanlder;

import com.zzl.alligator.common.constant.Constants;
import com.zzl.alligator.common.util.JsonUtils;
import com.zzl.alligator.common.util.SpringUtils;
import com.zzl.alligator.framework.async.AsyncManager;
import com.zzl.alligator.framework.security.LoginUser;
import com.zzl.alligator.framework.security.service.TokenService;
import com.zzl.alligator.framework.support.web.vo.JsonResult;
import com.zzl.alligator.management.system.domain.SysLoginRecord;
import com.zzl.alligator.management.system.service.ISysLoginRecordService;
import com.zzl.alligator.management.system.service.impl.SysLoginRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.TimerTask;

/**
 * TODO
 *
 * @author zhouziliang
 * @since 2020/6/28
 */
@Component
@Slf4j
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private TokenService tokenService;
    /**
     * Called when a user has been successfully authenticated.
     *
     * @param request        the request which caused the successful authentication
     * @param response       the response
     * @param authentication the <tt>Authentication</tt> object which was created during
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        log .info("登录成功！");

        LoginUser user = (LoginUser)authentication.getPrincipal();
        String token = tokenService.createToken(user);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write(JsonUtils.toJsonString(JsonResult.success("登录成功",
                token)));
        writer.flush();
        writer.close();
        AsyncManager.me().execute(new TimerTask() {
            @Override
            public void run() {
                ISysLoginRecordService recordService = SpringUtils.getBean(SysLoginRecordService.class);
                recordService.insertSysLoginRecord(SysLoginRecord.buildLoginRecord(request, user, Constants.SUCCESS,
                        "登录成功"));
            }
        });
    }
}
